﻿using System.Diagnostics;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters;
using System.Text;
using Microsoft.VisualBasic.FileIO;
using Test.Services.Implementation;
using SearchOption = System.IO.SearchOption;

namespace Test;

internal class Program {
    /// <summary>
    /// 临时后缀
    /// </summary>
    private const string TempSuffix = ".1";

    /// <summary>
    /// 临时后缀
    /// </summary>
    private const string ZipSuffix = ".zip";

    /// <summary>
    /// 加密文件路径
    /// </summary>
    private static readonly string EncryptedFilePath =
        Path.Combine(AppContext.BaseDirectory, "EncryptedFile.cs");

    private static async Task Main(string[] args) {
        var decryptService = new DecryptService(new LogService());
        while (true) {
            Console.Write("请输入文件夹路径:");
            var directory = Console.ReadLine()!;
            var decryptResult =
                await decryptService.DecryptDirectoryAsync(directory);
            Console.WriteLine($"{(decryptResult ? "解密成功" : "解密失败")}");
            Console.ReadKey();
            Console.Clear();
        }

        // File.Copy(EncryptedFilePath, EncryptedFilePath + TempSuffix);
        //
        // //删除被加密文件
        // try {
        //     File.Delete(EncryptedFilePath);
        // } catch (Exception e) {
        //     Console.WriteLine($"删除被加密文件失败,异常信息={e.Message}");
        //     throw;
        // }
        //
        // // 要压缩和修改名称的文件
        // var filePath = EncryptedFilePath + TempSuffix;
        //
        // // 压缩文件
        // var zipFilePath = CompressFile(filePath);
        //
        // // 在压缩包中修改文件名称
        // var newFileName = "EncryptedFile.cs";
        // ModifyFileNameInZip(zipFilePath, "EncryptedFile.cs.1", newFileName);
        //
        // string command = "tar";
        // string arguments = "-xzvf EncryptedFile.cs.zip";
        //
        // ExecuteShellCommand(command, arguments);
    }

    private static string CompressFile(string filePath) {
        var zipFilePath = $"{Path.GetFileNameWithoutExtension(filePath)}.zip";

        using (var fileStream = new FileStream(zipFilePath, FileMode.Create))
        using (var archive =
               new ZipArchive(fileStream, ZipArchiveMode.Create)) {
            // 将文件添加到压缩包中
            var entry = archive.CreateEntry(Path.GetFileName(filePath));

            using (var entryStream = entry.Open())
            using (var fileToCompress =
                   new FileStream(filePath, FileMode.Open)) {
                fileToCompress.CopyTo(entryStream);
            }
        }

        return zipFilePath;
    }

    private static void ModifyFileNameInZip(string zipFilePath,
        string oldFileName, string newFileName) {
        var tempZipFilePath = "temp.zip";

        using (var fileStream = new FileStream(zipFilePath, FileMode.Open))
        using (var oldArchive = new ZipArchive(fileStream, ZipArchiveMode.Read))
        using (var tempFileStream =
               new FileStream(tempZipFilePath, FileMode.Create))
        using (var newArchive =
               new ZipArchive(tempFileStream, ZipArchiveMode.Create)) {
            foreach (var entry in oldArchive.Entries)
                // 复制旧的 entry 数据到新的 entry
                if (entry.FullName != oldFileName) {
                    var newEntry = newArchive.CreateEntry(entry.FullName);

                    using (var newEntryStream = newEntry.Open())
                    using (var entryStream = entry.Open()) {
                        entryStream.CopyTo(newEntryStream);
                    }
                } else {
                    // 修改文件名称
                    var newEntry = newArchive.CreateEntry(newFileName);

                    using (var newEntryStream = newEntry.Open())
                    using (var entryStream = entry.Open()) {
                        entryStream.CopyTo(newEntryStream);
                    }
                }
        }

        // 删除原始压缩文件，将临时文件重命名为原始文件
        File.Delete(zipFilePath);
        File.Move(tempZipFilePath, zipFilePath);
    }

    private static void ExecuteShellCommand(string command, string arguments) {
        var psi = new ProcessStartInfo {
            FileName = command,
            Arguments = arguments,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        using (var process = Process.Start(psi)) {
            if (process != null) {
                var output = process.StandardOutput.ReadToEnd();
                var error = process.StandardError.ReadToEnd();

                process.WaitForExit();

                var exitCode = process.ExitCode;

                Console.WriteLine($"Command exited with code {exitCode}");
                Console.WriteLine("Output:");
                Console.WriteLine(output);
                Console.WriteLine("Error:");
                Console.WriteLine(error);
            }
        }
    }
}